package com.smzd.framework.core.actions;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.smzd.core.actions.AbstractDFController;
import com.smzd.core.domain.IntIdEntity;
import com.smzd.framework.annotation.ModuleGroup;
import com.smzd.framework.utils.MeetingDateTimeEditor;
import com.smzd.framework.utils.reflect.GenericHelper;

public abstract class AbstractCommonController<E extends IntIdEntity> extends AbstractDFController<E> {
    private static final String _VIEW_PARAMETER_KEY = "_view_";
    protected final Class<E> entityClass;
    protected final String moduleName;
    protected final String moduleNames;
    protected final String moduleGroup;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        MeetingDateTimeEditor dateEditor = new MeetingDateTimeEditor();
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    @SuppressWarnings("unchecked")
    protected AbstractCommonController() {
        entityClass = (Class<E>) GenericHelper.getActuralClass(this.getClass());
        String value = null;
        String mn = null;
        String mns = null;
        if (entityClass.isAnnotationPresent(ModuleGroup.class)) {
            ModuleGroup mg = entityClass.getAnnotation(ModuleGroup.class);
            value = mg.value();
            if (!value.endsWith("/")) {
                value += "/";
            }
            mn = mg.moduleName();
            mns = mg.moduleNames();
        }
        moduleGroup = value == null ? "" : value;
        moduleName = mn == null || mn.length() == 0 ? entityClass.getSimpleName().toLowerCase() : mn;
        moduleNames = mns == null || mns.length() == 0 ? moduleName + "s" : mns;
    }

    @Override
    protected String getListView(String view) {
        if (view == null) {
            view = moduleNames + ".ftl";
        }
        return getMyView(view);
    }

    @Override
    protected String getEditView(String view) {
        if (view == null) {
            view = moduleName + ".ftl";
        }
        return getMyView(view);
    }

    protected String getMyView(String ftl) {
        return moduleGroup + moduleNames + "/" + ftl;
    }

    protected static String getViewParameter(Map<String, Object> model) {
        Object obj = model.get(_VIEW_PARAMETER_KEY);
        String view = null;
        if (obj != null && obj instanceof String) {
            view = (String) obj;
        }
        return view;
    }

    protected static void setViewParameter(Map<String, Object> model, String view) {
        model.put(_VIEW_PARAMETER_KEY, view);
    }
}
